Page({
  data: {
    name: '',
    idType: '身份证',
    idNumber: '',
    phone: '',
    isEdit: false,
    index: -1
  },
  
  onLoad(options) {
    if (options.index !== undefined) {
      // 编辑模式
      const contacts = wx.getStorageSync('contacts') || []
      const contact = contacts[parseInt(options.index)]
      if (contact) {
        this.setData({
          isEdit: true,
          index: parseInt(options.index),
          name: contact.name,
          idType: contact.idType || '身份证',
          idNumber: contact.idNumber,
          phone: contact.phone
        })
      }
    }
  },
  
  onNameInput(e) {
    this.setData({
      name: e.detail.value
    })
  },
  
  selectIdType() {
    wx.showActionSheet({
      itemList: ['身份证', '护照', '港澳通行证', '台胞证'],
      success: (res) => {
        const types = ['身份证', '护照', '港澳通行证', '台胞证']
        this.setData({
          idType: types[res.tapIndex]
        })
      }
    })
  },
  
  onIdNumberInput(e) {
    this.setData({
      idNumber: e.detail.value
    })
  },
  
  onPhoneInput(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  
  save() {
    // 验证
    if (!this.data.name) {
      wx.showToast({
        title: '请输入真实姓名',
        icon: 'none'
      })
      return
    }
    
    if (!this.data.idNumber) {
      wx.showToast({
        title: '请输入证件号',
        icon: 'none'
      })
      return
    }
    
    if (!this.data.phone) {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none'
      })
      return
    }
    
    const contact = {
      name: this.data.name,
      idType: this.data.idType,
      idNumber: this.data.idNumber,
      phone: this.data.phone
    }
    
    let contacts = wx.getStorageSync('contacts') || []
    
    if (this.data.isEdit) {
      contacts[this.data.index] = contact
    } else {
      contacts.push(contact)
    }
    
    wx.setStorageSync('contacts', contacts)
    
    wx.showToast({
      title: '保存成功',
      icon: 'success'
    })
    
    setTimeout(() => {
      wx.navigateBack()
    }, 1500)
  }
})


